//
//  BirthdayView.swift
//  AppleDemo
//
//  Created by Just 花语 on 2025/10/27.
//

import SwiftUI
import SwiftData

struct BirthdayView:View {
//4_Birthday, .modelContainer(for: Friend.self)用于绑定 view 和 model，在 view 可以使用 @Query 和 @Environment 来访问数据
//   BirthdayView()
//        .modelContainer(for: Friend.self)

    @Query(sort: \Friend.birthDate) private var friends: [Friend]
    @Environment(\.modelContext) private var context
    
    @State private var newName = ""
    @State private var newDate = Date.now
    
    var body: some View {
        NavigationStack{
            List(friends){ friend in
                HStack{
                    if friend.isBirthdayToday{
                        Image(systemName: "birthday.cake")
                    }
                    Text(friend.name)
                        .bold(friend.isBirthdayToday)
                    Spacer()
                    Text(friend.birthDate, format: .dateTime.month(.wide).day().year())
                }
            }
            .navigationTitle("Birthdays")
            .safeAreaInset(edge: .bottom){
                VStack(alignment: .center,spacing: 20){
                    Text("New Birthday")
                        .font(.headline)
                    DatePicker(selection:$newDate){
                        TextField("Name",text:$newName)
                            .textFieldStyle(.roundedBorder)
                    }
                    Button("Save"){
                        let newFriend = Friend(name: newName, birthDate: newDate)
                        context.insert(newFriend)
                        newName = ""
                        newDate = .now
                    }
                    .bold()
                }
            }
        }
    }
}
#Preview{
    BirthdayView()
}
